import {
	createStore
} from 'vuex'
import QQMapWX from 'qqmap-wx-jssdk';
const qqmapsdk_key = 'GVSBZ-BFVR3-FNK3T-YHIYD-35IAV-WXBOD';
const qqmapsdk = new QQMapWX({
	key: qqmapsdk_key //我的应用 非客户的 仅开发使用
});

const tabBarList = [{
		"pagePath": "/pages/index/index",
		"iconPath": "static/images/tab-index.png",
		"selectedIconPath": "static/images/tab-index-a.png",
		"text": "首页"
	},
	{
		"pagePath": "/pages/list/list",
		"iconPath": "static/images/tab-list.png",
		"selectedIconPath": "static/images/tab-list-a.png",
		"text": "报单区"
	},
	{
		"pagePath": "/pages/mall/mall",
		"iconPath": "static/images/tab-mall.png",
		"selectedIconPath": "static/images/tab-mall-a.png",
		"text": "消费商城"
	},
	{
		"pagePath": "/pages/cart/cart",
		"iconPath": "static/images/tab-cart.png",
		"selectedIconPath": "static/images/tab-cart-a.png",
		"text": "购物车"
	},
	{
		"pagePath": "/pages/my/my",
		"iconPath": "static/images/tab-my.png",
		"selectedIconPath": "static/images/tab-my-a.png",
		"text": "我的"
	}
];
let _location = uni.getStorageSync('location') || {
	city_code: 530100,
	city_name: '昆明',
	province_code: 530000,
	province_name: '云南',
	longitude: '',
	latitude: '',
	district_code: '',
	district_name: '',
};
let _isAskLocation = uni.getStorageSync('isAskLocation') || false

let _token = uni.getStorageSync('token') || ''
let _userInfo = uni.getStorageSync('userInfo') || {}
let _citys = uni.getStorageSync('citys') || []
let _adcodeObj = uni.getStorageSync('adcodeObj') || []

let _historyAccount = uni.getStorageSync('historyAccount') || []
let _searchKeyWords = uni.getStorageSync('searchKeyWords') || []
let _cartNum = uni.getStorageSync('cartNum') || {}


let _systemInfo = uni.getSystemInfoSync();
let _statusBarHeight = _systemInfo.platform === 'android' ? _systemInfo.statusBarHeight : (_systemInfo.statusBarHeight +
	44);

const store = createStore({
	state: { //存放状态
		"username": "foo",
		"age": 18,
		$isAskLocation: _isAskLocation, //是否已询问过获取定位
		$location: _location,
		$tabBarList: tabBarList,
		$statusBarHeight: _statusBarHeight,
		$systemInfo: _systemInfo,
		$token: _token,
		$userInfo: _userInfo,
		$citys: _citys,
		$adcodeObj: _adcodeObj,
		$historyAccount: _historyAccount,
		$searchKeyWords:_searchKeyWords,
		$cartNum:_cartNum || {}
	},
	mutations: {
		set_searchKeyWord(state, data){
			let searchKeyWords = JSON.parse(JSON.stringify(state.$searchKeyWords));
			if(!searchKeyWords.includes(data)){
				searchKeyWords.push(data);
			}
			state.$searchKeyWords = searchKeyWords;
			uni.setStorageSync('searchKeyWords', searchKeyWords)
		},
		clear_searchKeyWords(state, data){
			state.$searchKeyWords = [];
			uni.setStorageSync('searchKeyWords', [])
		},
		set_location(state, data) {
			state.$location = data;
			uni.setStorageSync('location', data)
		},
		set_cartNum(state, data){
			state.$cartNum = data;
			uni.setStorageSync('cartNum', data)
		},
		set_token(state, data) {
			state.$token = data;
			uni.setStorageSync('token', data)
		},
		set_userInfo(state, data) {
			state.$userInfo = data;
			uni.setStorageSync('userInfo', data)
		},
		set_citys(state, data) {
			state.$citys = data;
			let adcodeObj = {};
			data.forEach(p => {
				p.children.forEach(c => {
					c.children.forEach(d => {
						adcodeObj[d.id] = {
							province: {
								id: p.id,
								name: p.name
							},
							city: {
								id: c.id,
								name: c.name
							},
							district: {
								id: d.id,
								name: d.name
							}
						}
					})
				})
			})
			// console.log(adcodeObj);
			state.$adcodeObj = adcodeObj;
			uni.setStorageSync('citys', data)
			uni.setStorageSync('adcodeObj', adcodeObj)
		},
		set_isAskLocation(state, data) {
			if (data) {
				uni.setStorageSync('isAskLocation', true)
				state.$isAskLocation = true;
			} else {
				state.$isAskLocation = false;
				try {
					uni.removeStorageSync('isAskLocation')
				} catch (e) {

				}
			}
		},
		add_historyAccount(state, data) {
			if (data) {
				let historyAccount = JSON.parse(JSON.stringify(state.$historyAccount));
				let i = historyAccount.findIndex(v => v.userName == data.userName)
				if (i != -1) {
					historyAccount.splice(i, 1)
				}
				historyAccount.unshift(data);
				state.$historyAccount = historyAccount;
				uni.setStorageSync('historyAccount', historyAccount)
			}
		}
	},
	getters: {
		get_historyAccount(state) {
			let historyAccount = state.$historyAccount;
			return historyAccount
		},
		get_location(state) {
			let location = state.$location;
			return location
		},
		get_isAskLocation(state) {
			let isAskLocation = state.$isAskLocation;
			return isAskLocation
		},
		get_isLogin(state) {
			let token = state.$token;
			let userInfo = state.$userInfo;
			if (token && userInfo.id) {
				return true
			} else {
				return false
			}
		},
		get_tabBarList() {
			let tabBarList = state.$tabBarList;
		},
		get_token(state) {
			let token = state.$token;
			return token
		},
		get_userInfo(state) {
			let userInfo = state.$userInfo;
			return userInfo
		},
		get_adcodeObj(state) {
			let adcodeObj = state.$adcodeObj;
			return adcodeObj
		},
		get_cartNum(state){
			let cartNum = state.$cartNum;
			return cartNum
		}
	},
	actions: {
		getCart(state,type){
			let p = {
				current:1,
				size:20,
				type:type
			}
			uni.$u.api.getCart(p).then(res => {
				let {
					code,
					msg,
					data
				} = res;
				if (code != 200) {
					uni.$u.toast(msg || '错误');
					return;
				}
				let cartNum = JSON.parse(JSON.stringify(state.getters.get_cartNum));
				cartNum[`type${type}`] = Number(data.total)
				store.commit('set_cartNum', cartNum)
			})
		},
		getUserInfo(state) {
			uni.$u.api.getUsersMe().then(res => {
				let {
					code,
					msg,
					data
				} = res;
				if (code != 200) {
					uni.$u.toast(msg || '错误');
					return;
				}
				let userInfo = JSON.parse(JSON.stringify(state.getters.get_userInfo));
				for (let key in data) {
					userInfo[key] = data[key]
				}
				store.commit('set_userInfo', userInfo)
			})
		},
		async getSelectChinaCity(state) {
			await uni.$u.api.commonSelectChinaCity().then(res => {
				store.commit('set_citys', res.data)
			})
		},
		getLocation(state) {
			uni.getLocation({
				type: 'wgs84', //gcj02
				success: function(res) {
					let {
						longitude,
						latitude
					} = res;
					uni.$u.api.getCityCode({
						lat: latitude,
						lng: longitude
					}).then(res => {
						let [province_name, city_name, district_name] = res.data
							.address_code;
						let [province_code, city_code, district_code] = res.data
							.address_name;
						store.commit('set_location', {
							city_code,
							city_name,
							province_code,
							province_name,
							district_code,
							district_name,
							longitude,
							latitude
						})
					})

					// qqmapsdk.reverseGeocoder({
					// 	// sig: 'KEY设置中生成的SK字符串', // 必填
					// 	location: {
					// 		latitude,
					// 		longitude
					// 	},
					// 	success(res) {
					// 		let adcode = res.result.ad_info.adcode;
					// 		try{
					// 			let adcodeData = state.getters.get_adcodeObj[adcode];
					// 			store.commit('set_location', {
					// 				city_code: adcodeData.city.id,
					// 				city_name: adcodeData.city.name,
					// 				province_code:adcodeData.province.id,
					// 				province_name: adcodeData.province.name,
					// 				district_code:adcodeData.district.id,
					// 				district_name:adcodeData.district.name,
					// 				longitude,
					// 				latitude
					// 			})
					// 		}catch(e){
					// 			console.log('行政区划代码查不到对应省市区')
					// 		}
					// 	},
					// 	fail(err) {},
					// 	complete() {}
					// })
					// console.log('当前位置的经度：' + res.longitude);
					// console.log('当前位置的纬度：' + res.latitude);
				},
				fail(res) {
					if (res.errMsg == "getLocation:fail auth deny") {
						uni.$u.toast('请授权位置信息');
						uni.openAppAuthorizeSetting({
							success(res) {
								console.log(res)
							},
							fail(res1) {
								console.log('openAppAuthorizeSetting-fail', res1);
							}
						})
					}
					console.log('getLocation-fail', res);
				}
			})
		},
		modal(state, content) {
			let params = {
				title: '提示',
				content: '',
				confirmColor: '#00BF9B',
				showCancel: true
			};
			if (typeof content == 'string') {
				params.content = content;
			}
			if (typeof content == 'object') {
				Object.assign(params, content);
			}

			return new Promise((resolve, reject) => {
				uni.showModal({
					...params,
					success: function(res) {
						if (res.confirm) {
							resolve();
						} else if (res.cancel) {
							reject()
						}
					}
				});
			})
		},
		logout(state) {
			state.commit('set_userInfo', null);
			state.commit('set_token', null);
			// this.commit('set_role', null);
		}
	}
})

export default store